use crate::{
    helpers::{create_ttr, wrap_url, Bot, Config},
    keyboards,
};
use anyhow::{Context, Result};
use db::{Db, PostRandom};
use teloxide::{
    prelude::*,
    types::UserId,
    utils::markdown::{escape, escape_link_url},
};
use tracing::info;

pub async fn random(bot: Bot, m: Message, db: Db, _config: Config) -> Result<()> {
    let user_id = m.from().context("get user id NoneError")?.id;
    // let user_id = db::models::MatrixOrTelegramId::TelegramId { id: telegram_id, username: None };
    match db.get_random_post_tg(&user_id).await? {
        Some(post) => {
            send_post(&bot, post, user_id).await?;
        }
        None => all_posts_viewed(&bot, user_id).await?,
    }
    Ok(())
}
pub async fn send_post(bot: &Bot, post: PostRandom, user_id: UserId) -> Result<()> {
    // let ttr = count_ttr(post.word_count);
    let url = post.real_url;
    let mut answer = {
        if let Some(title) = post.title {
            info!("{:#?}", title);
            wrap_url(&url, &title)
        } else {
            escape(&escape_link_url(&url))
        }
    };
    if let Some(ttr) = post.word_count {
        create_ttr(&mut answer, ttr.try_into().unwrap())
    };
    info!("answer: {}", answer);
    bot.send_message(user_id, answer)
        .reply_markup(keyboards::standart_keyboard(
            &post.id.hyphenated().to_string(),
            post.read,
            post.favorite,
            post.show_alternative_url,
        ))
        // .parse_mode(MarkdownV2)
        .await?;
    Ok(())
}
async fn all_posts_viewed(bot: &Bot, user_id: UserId) -> Result<()> {
    bot.send_message(user_id, "All unread posts vieved!")
        .await?;
    Ok(())
}
// fn original_or_real(user: &UserRandom, post: &UserPostRandom) -> bool {
//     user.show_real_url || post.show_real_url
// }
